package com.wf.netty.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * handler
 *
 * @author wf
 * @since 2022/4/19
 */
@ChannelHandler.Sharable
public class MyServerChannelHandler extends ChannelInboundHandlerAdapter {
    public static final MyServerChannelHandler INSTANCE = new MyServerChannelHandler();

    private static final Logger LOGGER = LoggerFactory.getLogger(MyServerChannelHandler.class);

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道注册");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道激活");
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 接收客户端发来的数据
        System.out.println("step in");
        ByteBuf in = (ByteBuf) msg;


//        LOGGER.info("received from client: {}", in.readInt());

//        ByteBuf in = (ByteBuf) msg;
        LOGGER.info("msg type: " + (in.hasArray()?"堆内存":"直接内存"));
        int len = in.readableBytes();
        ByteBuf byteBuf = in.readBytes(len);
        LOGGER.info("server received: " + byteBuf.toString(StandardCharsets.UTF_8));

        LOGGER.info("写回前，msg.refCnt:" + ((ByteBuf) msg).refCnt());
        //写回数据，异步任务
        ChannelFuture f = ctx.writeAndFlush(msg);
        f.addListener((ChannelFuturefutureListener) -> {
            LOGGER.info("写回后，msg.refCnt:" + ((ByteBuf) msg).refCnt());
        });
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 创建消息
        ByteBuf byteBuf = Unpooled.copiedBuffer("Received", CharsetUtil.UTF_8);

        // 写入缓存并冲刷到客户端
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端处理异常: " + cause.getMessage());

        // 发生异常，关闭通道
        ctx.channel().close();
    }


}
